<?php

namespace app\common\model;

use think\Exception;
use think\Model;


class DestoryOrder extends Model
{

    

    

    // 表名
    protected $name = 'destory_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'destory_time_text',
	    'status_text'
    ];
    
	const STATUS_WAIT = 1;
	const STATUS_SUCCESS = 2;
	const STATUS_CLOSE = 0;
 
	public static $statusList = [
		self::STATUS_WAIT => '待核销',
		self::STATUS_SUCCESS => '已核销',
		self::STATUS_CLOSE => '已关闭'
	];

	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = self::$statusList;
		return $list[$value] ?? '';
	}


    public function getDestoryTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['destory_time']) ? $data['destory_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setDestoryTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
	
	public function agent() {
		return $this->belongsTo('agentShop', 'agent_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	/**
	 * 关闭待核销订单，创建新订单
	 * @param $orderId
	 * @param $number
	 * @return bool|string
	 * @throws \think\exception\PDOException
	 */
    public function createOrder($orderId, $number) {
		$this->startTrans();
		try {
			//更改未核销的为关闭
			$statusRes = $this->save(
				['status' => self::STATUS_CLOSE],
				['order_id' => $orderId, 'status' => self::STATUS_WAIT]);
			if($statusRes === false) {
				throw new Exception('更新旧状态出错');
			}
			
			$code =time().mt_rand(10000, 99999);
			$res = $this->isUpdate(false)
				->save([
					'order_id' => $orderId,
					'code' => $code,
					'number' => $number,
					'status' => self::STATUS_WAIT
				]);
			
			if(!$res) {
				throw new Exception('添加核销订单出错');
			}
			
			$this->commit();
			return $code;
		} catch (Exception $e) {
			$this->rollback();
			$this->error = $e->getMessage();
			return false;
		}
    }
}
